﻿using System;
using System.Web.UI.WebControls;
using MS.InformationManagement.Presenter.DocumentTypeUploader;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Support;
using MS.InformationManagement.Support.Constants;

namespace MS.InformationManagement.WP.RecordCenter.DocumentTypeUploader
{
    public partial class DocumentTypeUploaderUserControl : BaseControl, IDocumentTypeUploaderView
    {
        #region [Private Fields]

        private DocumentTypeUploaderPresenter _Presenter;

        #endregion

        #region [Event Handlers]

        protected void btnSubmitOperation_Click(object sender, EventArgs e)
        {
            try
            {

                if (DataIsValid())
                {

                    if (this.ItemID == null)
                    {
                        _Presenter.AddDocumentType();
                        HandleSuccess("El tipo de documento ha sido cargado exitosamente", new WebControl[] { btnSave });
                    }
                    else
                    {
                        _Presenter.UpdateDocumentType();
                        HandleSuccess("El tipo de documento ha sido actualizado exitosamente", new WebControl[] { btnSave });
                    }

                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void btnCancelOperation_Click(object sender, EventArgs e)
        {
            string isDlg = Request.QueryString.Get("IsDlg");
            if (!string.IsNullOrEmpty(isDlg) && isDlg.Equals("1")) { this.CloseWindow(); }
            else { this.GoCurrentUserHome(); }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                try
                {
                    _Presenter.HandleLoad();
                }
                catch (Exception ex)
                {
                    HandleError(ex);
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Page.RegisterAjaxLoaderPlugin();
            _Presenter = new DocumentTypeUploaderPresenter(this);
            txtbTitle.Required(ExceptionConstants.ERROR_CAMPO_NULO,"ValidationGroup", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            txtbCode.Required(ExceptionConstants.ERROR_CAMPO_NULO, "ValidationGroup", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            txtbVersion.Required(ExceptionConstants.ERROR_CAMPO_NULO, "ValidationGroup", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            txtbVersion.Numeric("999", false);
            btnSave.AddLoader();
        }

        #endregion

        #region Private Methods

        private bool DataIsValid()
        {
            bool result = DateValidation();
            result = result && IsFileValid();
            return result;
        }

        private bool DateValidation()
        {
            if (!dtpCreationDate.IsDateEmpty)
                return true;

            HandleWarning("Debe ingresar una fecha de creación valida");
            return false;
        }

        #endregion

        #region [IDocumentTypeUploaderView Members]

        public int? ItemID
        {
            get
            {
                return string.IsNullOrEmpty(Request.QueryString.Get("ID")) ? new Nullable<Int32>() : Convert.ToInt32(Request.QueryString.Get("ID"));
            }
        }

        public string Title
        {
            get
            {
                return txtbTitle.Text;
            }
            set
            {
                txtbTitle.Text = value;
            }
        }

        public string FileName
        {
            get { return htmlFileTemplate.FileName; }
        }

        public string Code
        {
            get
            {
                return txtbCode.Text;
            }
            set
            {
                txtbCode.Text = value;
            }
        }

        public double? Version
        {
            get
            {
                return string.IsNullOrEmpty(txtbVersion.Text) ? new Nullable<Double>() : Convert.ToDouble(txtbVersion.Text);
            }
            set
            {
                txtbVersion.Text = value.HasValue ? value.Value.ToString() : string.Empty;
            }
        }

        public DateTime? CreationDate
        {
            get
            {
                return dtpCreationDate.IsDateEmpty ? new Nullable<DateTime>() : dtpCreationDate.SelectedDate;
            }
            set
            {
                if (value.HasValue) { dtpCreationDate.SelectedDate = value.Value; }
            }
        }

        public System.IO.Stream FileInputStream
        {
            get { return htmlFileTemplate.PostedFile == null || htmlFileTemplate.PostedFile.ContentLength == 0 ? null : htmlFileTemplate.PostedFile.InputStream; }
        }

        public string Extension
        {
            get
            {
                if (htmlFileTemplate.PostedFile == null) { return string.Empty; }

                string fileName = htmlFileTemplate.PostedFile.FileName;
                int startIndex = fileName.LastIndexOf('.') + 1;
                string extension = fileName.Substring(startIndex);
                return extension;
            }
        }

        public string Operation
        {
            get
            {
                return frmTitle.InnerText;
            }
            set
            {
                frmTitle.InnerText = value;
            }
        }

        public bool IsFileValid()
        {
            bool isValid = true;
            if (this.ItemID == null)
            {
                if (FileInputStream == null)
                {
                    HandleWarning("Debe seleccionar una plantilla antes de realizar el proceso de carga");
                    isValid = false;
                    return isValid;
                }

                string fileExtension = Extension;
                switch (fileExtension)
                {
                    case GlobalConstants.WORD:
                    case GlobalConstants.WORD_LEGACY:
                    case GlobalConstants.EXCEL:
                    case GlobalConstants.EXCEL_LEGACY:
                    case GlobalConstants.POWERPOINT:
                    case GlobalConstants.POWERPOINT_LEGACY:
                        break;
                    default:
                        isValid = false;
                        HandleWarning("La extensión del archivo que intenta cargar no es válida. Recuerde que solo puede cargar archivos con extensión .ppt, .pptx, .doc, .docx, .xls, .xlsx");
                        break;
                }
            }
            else
            {
                string fileExtension = Extension;
                if (!string.IsNullOrEmpty(fileExtension))
                {
                    switch (fileExtension)
                    {
                        case GlobalConstants.WORD:
                        case GlobalConstants.WORD_LEGACY:
                        case GlobalConstants.EXCEL:
                        case GlobalConstants.EXCEL_LEGACY:
                        case GlobalConstants.POWERPOINT:
                        case GlobalConstants.POWERPOINT_LEGACY:
                            break;
                        default:
                            isValid = false;
                            HandleWarning("La extensión del archivo que intenta cargar no es válida. Recuerde que solo puede cargar archivos con extensión .ppt, .pptx, .doc, .docx, .xls, .xlsx");
                            break;
                    }
                }
            }

            return isValid;
        }

        #endregion
    }
}
